document.getElementById('login').addEventListener('click', () => {
    const url = '/api/v1/login'
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const data = {
        username: username,
        password: password
    };
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=UTF-8'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            if (response.status == 400) {
                throw new Error(`参数错误`)
            } else if (response.status == 401) {
                throw new Error(`无效的登陆凭据`)
            } else {
                throw new Error(`未知错误，状态码： ${response.status}`);
            }
        }
        return response.json();
    })
    .then(result => { // 成功
        localStorage.setItem('jwt_token', result.token)
        window.open('/index.html', '_self')
    })
    .catch(error => {
        alert(error)
    })
});

document.getElementById('regiest').addEventListener('click', () => {
    const url = '/api/v1/regiest';
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const data = {
        username: username,
        password: password
    };
    fetch(url, {
        method: "POST",
        headers: {
            'Content-Type': 'application/json; charset=UTF-8'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            if (response.status == 400) {
                throw new Error(`参数错误`)
            } else if (response.status == 409) {
                throw new Error(`用户已存在`)
            } else {
                throw new Error(`未知错误，状态码： ${response.status}`);
            }
        }
        return response.json();
    })
    .then(result => {
        alert('注册成功')
        localStorage.setItem('jwt_token', result.token)
        window.open('/index.html', '_self')
    })
    .catch(error => {
        alert(error)
    })
})